//
//  HomeCenterCell.m
//  GoldOperationClient
//
//  Created by yaxue wang on 2016/11/24.
//  Copyright © 2016年 展鸿科技. All rights reserved.
//

#import "HomeCenterCell.h"
#import "HomeModel.h"
#import "VoiceConverter.h"
#import <AFNetworking/AFURLSessionManager.h>
#import <UIImageView+AFNetworking.h>
@interface HomeCenterCell()
@property (nonatomic, strong) UIImageView *img1;
@property (nonatomic, strong) UIImageView *img2;
@property (nonatomic, strong) UIImageView *img3;
@property (nonatomic, strong) UIImageView *viedoImg;
@property (nonatomic, strong) UIImageView *defautViedoImg;
@property (nonatomic, strong) UILabel *contextLab;
@property (nonatomic, strong) UILabel *equipmentLab;
@property (nonatomic, strong) UILabel *videoCompressLab;
@property (nonatomic, strong) UIImageView *soundView;
@property (nonatomic, strong) UIImageView *soundImg;
@property (nonatomic, strong) UILabel *soundTimeLab;
@property (nonatomic, strong) UIView *bleowView;

@property (nonatomic, strong)AVAudioPlayer *audioPlayer;
@end
@implementation HomeCenterCell
- (void)initView{
    [super initView];
    self.backgroundColor =[UIColor whiteColor];
    self.equipmentLab=[[UILabel alloc]init];
    [self addSubview:self.equipmentLab];

    self.equipmentLab.font =F(12);
    self.equipmentLab.textColor =FontColor;
    self.equipmentLab.numberOfLines=0;
    
    self.contextLab = [[UILabel alloc] init];
    [self addSubview:self.contextLab];
    self.contextLab.numberOfLines=0;
    self.contextLab.textColor =FontColor;
    self.contextLab.font =F(12);
    
    UIImage *sound=[UIImage imageNamed:@"Ico_home_ soundBg"];
    
//    self.soundBg=[[UIView alloc]init];
//    [self addSubview:self.soundBg];
//
//    [self.soundBg mas_makeConstraints:^(MASConstraintMaker *make) {
//        make.left.equalTo(self.contextLab);
//        make.top.equalTo(self.contextLab.mas_bottom).offset(5);
//        make.right.equalTo(self);
//    }];
//    self.soundBg.backgroundColor=[UIColor redColor];
    
    self.soundView =[[UIImageView alloc]init];
    [self addSubview:self.soundView];
    [self.soundView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.contextLab);
        make.top.equalTo(self.contextLab.mas_bottom).offset(5);
        make.size.mas_equalTo(CGSizeMake(sound.size.width,30));
    }];
    self.soundView.userInteractionEnabled=YES;
    self.soundView.image=sound;
    [self.soundView bk_whenTapped:^{
        if (self.btnBlock) {
            self.btnBlock(self,HomeCellType_Sound,nil);
        }
    }];

    self.soundImg =[[UIImageView alloc]initWithFrame:CGRectMake(15, 0, 30, 30)];
    //定义数组，存放所有图片对象
    NSArray *images=[NSArray arrayWithObjects:[UIImage imageNamed:@"Ico_home_ sonic1"],[UIImage imageNamed:@"Ico_home_ sonic2"],[UIImage imageNamed:@"Ico_home_ sonic3"],nil];
    self.soundImg.image =[UIImage imageNamed:@"Ico_home_ sonic3"];
    //imageView的动画图片是数组images
    self.soundImg.animationImages = images;
    //按照原始比例缩放图片，保持纵横比
    self.soundImg.contentMode = UIViewContentModeScaleAspectFit;
    //切换动作的时间3秒，来控制图像显示的速度有多快，
    self.soundImg.animationDuration = 3;
    //动画的重复次数，想让它无限循环就赋成0
    self.soundImg.animationRepeatCount = 0;
    //添加控件
    [self.soundView addSubview:self.soundImg];
    self.soundImg.userInteractionEnabled=YES;
    self.soundTimeLab=[[UILabel alloc]init];
    [self addSubview:self.soundTimeLab];
    [self.soundTimeLab mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.equalTo(self.soundView.mas_right).offset(10);
        make.top.equalTo(self.soundView);
        make.centerY.equalTo(self.soundView);
        make.right.equalTo(self).offset(-15);
    }];
    self.soundTimeLab.textColor=LightFontColor;
    self.soundTimeLab.font=F(10);
    
    self.videoCompressLab=[[UILabel alloc]init];
    [self addSubview:self.videoCompressLab];

    self.videoCompressLab.numberOfLines=0;
    self.videoCompressLab.textColor =FontColor;
    self.videoCompressLab.font =F(12);
    
    self.img1 =[[UIImageView alloc]init];
    self.img1.tag=200;
    self.img1.userInteractionEnabled=YES;
    [self addSubview:self.img1];

    self.img2 =[[UIImageView alloc]init];
    self.img2.tag=300;
    self.img2.userInteractionEnabled=YES;
    [self addSubview:self.img2];
    
    self.img3 =[[UIImageView alloc]init];
    self.img3.userInteractionEnabled=YES;
    self.img3.tag=400;
    [self addSubview:self.img3];
    self.viedoImg =[[UIImageView alloc]init];
    self.viedoImg.userInteractionEnabled=YES;
    self.viedoImg.tag=500;
    [self addSubview:self.viedoImg];

    
    UIImage *image = [UIImage imageNamed:@"Ico_home_play"];
    self.defautViedoImg = [[UIImageView alloc] init];
    [self.viedoImg addSubview:self.defautViedoImg];
    self.defautViedoImg.userInteractionEnabled=YES;
  
    self.defautViedoImg.contentMode = UIViewContentModeScaleAspectFill;
    self.defautViedoImg.image=image;
   
    [self bk_whenTapped:^{
        if (self.btnBlock) {
            self.btnBlock(self,HomeCellType_Detail,nil);
        }
        
    }];

    
    
    
    
   
}
- (void)setModel:(id)model{
    HomeModel *order = model;
    NSString*urlString =[CClass getCacheData:qnDomain];
    NSString *equitString;
    NSString *textDescride;
    CGFloat equitHeight;
    CGFloat describeHeight;
//    if ([order.H_order_type isEqualToString:@"1"]) {
    
    
//    }else
//    {
//       
//        [self bk_whenTapped:^{
//            if (self.btnBlock) {
//                self.btnBlock(self,HomeCellType_DetailPolling,nil);
//            }
//            
//        }];
//        
//        
//    }
    
    if ((order.H_machine_name ==nil||[order.H_machine_name isEqualToString:@""])&&(order.H_machine_type_name ==nil||[order.H_machine_type_name isEqualToString:@""])) {
        self.equipmentLab.text =@"";
        equitString=@"";
        equitHeight=0;
    }else if ((order.H_machine_name ==nil||[order.H_machine_name isEqualToString:@""])||(order.H_machine_type_name ==nil||[order.H_machine_type_name isEqualToString:@""])) {
        
        if(order.H_machine_name ==nil||[order.H_machine_name isEqualToString:@""]){
            equitString=[NSString stringWithFormat:@"%@",order.H_machine_type_name];
            equitHeight=15+10;
            
        }else if(order.H_machine_type_name ==nil||[order.H_machine_type_name isEqualToString:@""]){
            equitString =[NSString stringWithFormat:@"%@",order.H_machine_name];
            equitHeight=15+10;
            
            
        }
        
    }else
    {
        equitString =[NSString stringWithFormat:@"%@  %@",order.H_machine_type_name,order.H_machine_name];
        CGSize equitmetSize  = [equitString sizeWithFont:F(12) constrainedToSize:CGSizeMake(WindowWidth-95, 900)];
        equitHeight=equitmetSize.height+10;
        
    }
    self.equipmentLab.text =equitString;
    self.equipmentLab.frame=CGRectMake(80, 2, WindowWidth-80-15, equitHeight);
    
    if ((order.H_textdescribe ==nil||[order.H_textdescribe isEqualToString:@""])) {
        textDescride=@"";
        describeHeight=0;
    }else
    {
        textDescride=order.H_textdescribe;
        CGSize descrideSize  = [textDescride sizeWithFont:F(12) constrainedToSize:CGSizeMake(WindowWidth-95, 900)];
        describeHeight= descrideSize.height+10;
        
        
    }
    self.contextLab.frame=CGRectMake(80, equitHeight, WindowWidth-95,describeHeight);
    
    
    self.contextLab.text=textDescride;
    NSString *soundData=order.H_audio;
    CGFloat soundHeight;

    if ((soundData ==nil||[soundData isEqualToString:@""])) {
        soundHeight=10;
        self.soundView.hidden=YES;
        self.soundTimeLab.hidden=YES;
        self.videoCompressLab.hidden=YES;

    }else
    {
        self.soundView.hidden=NO;
        self.soundTimeLab.hidden=NO;
        self.soundTimeLab.text=@"";
        if ((order.H_audio_translator ==nil||[order.H_audio_translator isEqualToString:@""])) {
            soundHeight=40;
        }else
        {
            self.videoCompressLab.hidden=NO;
            NSString *string=[NSString stringWithFormat:@"(%@)",order.H_audio_translator];
            CGSize videocompressSize  = [string sizeWithFont:F(12) constrainedToSize:CGSizeMake(WindowWidth-95, 900)];
            self.videoCompressLab.frame=CGRectMake(80, CGRectGetMaxY(self.contextLab.frame)+40, WindowWidth-95, videocompressSize.height);
            self.videoCompressLab.text=string;
            soundHeight=videocompressSize.height+40+5;
            
        }
        
      
   
      
    }
    __block typeof(soundData) blockself = soundData;
        
    NSString*imgStr=order.H_image;
    NSString *videoStr=order.H_video;
    CGFloat width =(WindowWidth-95-30)/3;
    NSArray *views = @[self.img1, self.img2, self.img3, self.viedoImg];
    for (UIView *view in views) {
        
        [view removeFromSuperview];
        
    }
    
    NSMutableArray *array;
    if ((imgStr ==nil||[imgStr isEqualToString:@""])) {
        [array removeAllObjects];
    }else
    {
        array =(NSMutableArray *)[imgStr componentsSeparatedByString:@","];
    }
    NSMutableArray *viewarray = [NSMutableArray array];
    for (int i = 0; i < array.count; i ++) {
        [viewarray addObject:views[i]];
    }
    if (videoStr.length > 0) {
        [viewarray addObject:self.viedoImg];
    }
    int i = 0;
    for (UIImageView *view in viewarray) {
        [self addSubview:view];
        view.frame=CGRectMake(80+(i%3)*(10+width),  CGRectGetMaxY(self.contextLab.frame)+soundHeight + (width+10) * (i / 3), width, width);
        
        i ++;
        NSString *num=[NSString stringWithFormat:@"%d",i-1];
        
        [view bk_whenTapped:^{
           
            if (self.btnBlock) {
                self.btnBlock(self,HomeCellType_Img,num);
            }
        }];
#pragma mark 获取视频
        
        if (i==viewarray.count && array.count + 1 == viewarray.count) {
            NSURL *videoUrl =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,videoStr]];
            [self centerFrameImageWithVideoURL:videoUrl completion:^(UIImage *image) {
                view.image= image;
            }];
            UIImage *image = [UIImage imageNamed:@"Ico_home_play"];
            self.defautViedoImg.frame=CGRectMake((width-image.size.width)/2, (width-image.size.height)/2, image.size.width, image.size.height);
            
            
            
        }else{
            
        }
        if(i<=array.count)
        {
#pragma mark 获取图片
            
            NSURL *url =[NSURL URLWithString:[NSString stringWithFormat:@"%@%@",urlString,[array objectAtIndex:i-1]]];
            [view sd_setImageWithURL:url placeholderImage:[UIImage imageNamed:@"ico_home_defa"]];
            
        
        }else{
            
        }
//        
//        self.bleowView.frame=CGRectMake(0,CGRectGetMaxY(self.contextLab.frame)+soundHeight + (width+10) * (i / 3)+10, WindowWidth, 35);
 
    }
    
    

    
   
}
#pragma mark  异步获取帧图片，可以一次获取多帧图片
- (void)centerFrameImageWithVideoURL:(NSURL *)videoURL completion:(void (^)(UIImage *image))completion {
    // AVAssetImageGenerator
    AVAsset *asset = [AVAsset assetWithURL:videoURL];
    AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset];
    imageGenerator.appliesPreferredTrackTransform = YES;
    
    // calculate the midpoint time of video
    Float64 duration = CMTimeGetSeconds([asset duration]);
    // 取某个帧的时间，参数一表示哪个时间（秒），参数二表示每秒多少帧
    // 通常来说，600是一个常用的公共参数，苹果有说明:
    // 24 frames per second (fps) for film, 30 fps for NTSC (used for TV in North America and
    // Japan), and 25 fps for PAL (used for TV in Europe).
    // Using a timescale of 600, you can exactly represent any number of frames in these systems
    CMTime midpoint = CMTimeMakeWithSeconds(duration / 2.0, 600);
    
    // 异步获取多帧图片
    NSValue *midTime = [NSValue valueWithCMTime:midpoint];
    [imageGenerator generateCGImagesAsynchronouslyForTimes:@[midTime] completionHandler:^(CMTime requestedTime, CGImageRef  _Nullable image, CMTime actualTime, AVAssetImageGeneratorResult result, NSError * _Nullable error) {
        if (result == AVAssetImageGeneratorSucceeded && image != NULL) {
            UIImage *centerFrameImage = [[UIImage alloc] initWithCGImage:image];
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(centerFrameImage);
                }
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                if (completion) {
                    completion(nil);
                }
            });
        }
    }];
}
- (void)stopPlayer
{
    self.soundTimeLab.text=@"";
   [self.soundImg stopAnimating];

}

- (void)startAnimate:(id)data{
    [self.soundImg startAnimating];
    self.soundTimeLab.text =data;
}
@end
